package books

class BookService {

	boolean transactional = true
	
	def getStaticBook() {
		return new Book(title: "Old MacDonald had a farm", author: "Some guy", 
			description: "A story about a farmer and his animals", minGradeLevel: 0,
			maxGradeLevel: 6, language: "English", category: "General Leisure Reading")
	}
	
	def getRandomBook() {
		
		def allBooks = Book.list()
		def randomBook = null
		
		if (allBooks.size() > 0) {
			def randomIdx = new Random().nextInt(allBooks.size())
			randomBook = allBooks[randomIdx]
		}
		else {
			randomBook = getStaticBook()
		}
		return randomBook
	}
	
	def getValidISBN(string) {		
		def pattern1 =  ~/(?=.{13}$)97(?:8|9)\d\d\d\d\d\d\d\d\d\d$/
		def pattern2 = ~/(?=.{10}$)97(?:8|9)\d\d\d\d\d\d\d$/
		
		if (pattern1.matcher(string).matches() || pattern2.matcher(string).matches())
			return true
		return false
	}
}
